<template>
    <div class="gold-shop-wrap">
        <van-nav-bar title="联盟商家" left-arrow fixed @click-left="onClickLeft" />
        <div class="profit_core">
            <div class="profit_core_title">
                <div>所属联盟：<span @click="showUnion = true">{{ unionName }}<van-icon name="arrow-down" /></span> </div>
            </div>
            <div class="profit_core_amt">
                <div class="profit_core_amt_list after">
                    <div>{{statistics.today_order}}</div>
                    <div>今日订单数</div>
                </div>
                <div class="profit_core_amt_list after">
                    <div>{{statistics.today_amount}}</div>
                    <div>今日营业额</div>
                </div>
                <div class="profit_core_amt_list after">
                    <div>{{statistics.month_amount>100000?(statistics.month_amount/10000).toFixed(2)+'w':statistics.month_amount}}</div>
                    <div>本月营业额</div>
                </div>
                <div class="profit_core_amt_list">
                    <div>{{statistics.history_amount>100000?(statistics.history_amount/10000).toFixed(2)+'w':statistics.history_amount}}</div>
                    <div>总营业额</div>
                </div>
            </div>
        </div>
        <div>
            <div class="profit_core_title1">联盟近7日营业额/订单趋势</div>
            <div class="chart_box">
                <div ref="chart" style="width: 100%; height: 230px;"></div>
            </div>
        </div>
        <div>
            <div class="profit_core_title1">联盟月度营业额分析</div>
            <div class="chart_box">
                <div ref="chartCategory" style="width: 100%; height: 200px;"></div>
            </div>
        </div>
        <div>
            <div class="profit_core_title1">商家列表({{total_count}})</div>
            <div>
                <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                    <div class="order_all" v-for="item,index in shopList" :key="index" :title="item">
                        <div class="order_name_return">
                            <div class="order_name_left">{{item.name}}</div>
                            <div class="balance_amt">{{item.region_name}}</div>
                        </div>
                        <div class="ectension_list">
                            <div class="ectension_list_item">
                                <div>{{item.today_order}}</div>
                                <div class="ectension_list_item_title">今日订单数</div>
                            </div>
                            <div class="ectension_list_item">
                                <div>{{item.today_amount}}</div>
                                <div class="ectension_list_item_title">今日营业额</div>
                            </div>
                            <div class="ectension_list_item">
                                <div>{{item.month_amount>100000?(item.month_amount/10000).toFixed(2)+'w':item.month_amount}}</div>
                                <div class="ectension_list_item_title">本月营业额</div>
                            </div>
                            <div class="ectension_list_item">
                                <div>{{item.history_amount>100000?(item.history_amount/10000).toFixed(2)+'w':item.history_amount}}</div>
                                <div class="ectension_list_item_title">总营业额</div>
                            </div>
                        </div>
                    </div>
                </van-list>
            </div>
        </div>
        <van-popup v-model="showUnion" position="bottom" :style="{ height: '30%' }">
            <van-picker title="所属联盟" :value="type" show-toolbar value-key="name"
                :columns="columns" @confirm="onConfirm" @cancel="onCancel" />
        </van-popup>
    </div>
</template>
<script>
import {ALLIANCE_SHOP_LIST,ALLIANCE_INFO,ALLIANCE_STATISTICS} from '@/api/mine'
import * as echarts from 'echarts';
export default{
    data() {
        return {
            finished:false,
            loading:false,
            amountList:{},
            page:1,
            pageSize:20,
            shopList:[],
            total_count:0,
            level_name:this.$route.query.level_name,
            unionName:"全部联盟",
            showUnion:false,
            type:0,
            columns:[],
            statistics:{},
            dateAmount:[],
            dateCount:[],
            dateDate:[],
            yearAmount:[],
            yearDate:[]
        }
    },
    mounted() {
    window.scrollTo(0, 0)
    this.$http.get(ALLIANCE_INFO).then(res=>{
      this.columns=res.data
    })
    this.getAllianceStatistics(0)
        //
    },
    beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose(); // 组件销毁时销毁 ECharts 实例
    }
    if (this.chartInstanceCate) {
      this.chartInstanceCate.dispose(); // 组件销毁时销毁 ECharts 实例
    }
  },
    methods: {
     getAllianceStatistics(code){
        this.$http.get(ALLIANCE_STATISTICS+code).then(res=>{
            this.statistics=res.data.statistics
            this.dateAmount=res.data.chart_day7.map(item => item.amount);
            this.dateCount=res.data.chart_day7.map(item => item.count);
            this.dateDate=res.data.chart_day7.map(item => item.date);
            this.yearAmount=res.data.chart_year.map(item => item.amount);
            this.yearDate=res.data.chart_year.map(item => item.date);
            this.initChart();
            this.initChartCategory()
        })
      },
      // 所属联盟
      onConfirm(val){
        // console.log(val);
        this.unionName=val.name
        this.type=val.code
        this.getAllianceStatistics(val.code)
        this.page=1
        this.shopList=[]
        this.onLoad()
        this.showUnion=false
      },
      onCancel(){
        this.showUnion=false
      },
      initChart() {
  const chartDom = this.$refs.chart;
  this.chartInstance = echarts.init(chartDom);

  const maxAmount = (Math.max(...this.dateAmount) * 1.1).toFixed(2); // 增加 10% 的缓冲
  const maxCount = (Math.max(...this.dateCount) * 1.5).toFixed(0); // 增加 10% 的缓冲，如果没有有效值则设置为100

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        let tooltipContent = '';
        params.forEach(item => {
          let value = item.data; // 获取数据点
          if (item.seriesName === '营业额') {
            value = (value / 10000).toFixed(2) + ' w'; // 仅对营业额进行格式化
          }
          tooltipContent += `${item.seriesName}: ${value}<br/>`; // 拼接 tooltip 内容
        });
        return tooltipContent; // 返回格式化后的 tooltip 内容
      }
    },
    legend: {
      data: ['营业额', '订单数量'],
      top: '0%',  // 设置图例位置为上方
      right: '5%',  // 设置图例位置为右边
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: this.dateDate
    },
    yAxis: [
    {
      type: 'value',
      name: '营业额',
      min: 0,
      max:Math.max(10000,maxAmount),
      // interval: 50,
      axisLabel: {
          formatter: function(value) {
            return (value / 10000).toFixed(2) + ' w'; // 将值除以10000并添加单位
          }
        },
    },
    {
      type: 'value',
      name: '订单数量',
      min: 0,
      max: maxCount,
      // interval: 5,
      axisLabel: {
        formatter: function(value) {
            return value; // 对订单数量不进行格式化
          }
      }
    }
  ],
  series: [
    {
      name: '营业额',
      type: 'line',
      // tooltip: {
      //   valueFormatter: function (value) {
      //     return value + ' ml';
      //   }
      // },
      data: this.dateAmount,
        itemStyle: {
          color: '#F32A23',  // 设置折线颜色为红色
        },
    },
    {
      name: '订单数量',
      type: 'line',
      yAxisIndex: 1,
        type: 'line',
        data: this.dateCount,
        itemStyle: {
          color: '#FEB900',  // 设置折线颜色为黄色
        },
    }
  ],
    // yAxis: [
    //   {
    //     type: 'value',
    //     name: '营业额',
    //     min: 0,
    //     max: maxAmount,
    //     axisLabel: {
    //       formatter: function(value) {
    //         return (value / 10000).toFixed(2) + ' w'; // 将值除以10000并添加单位
    //       }
    //     },
    //   },
    //   {
    //     type: 'value',
    //     name: '订单数',
    //     min: 0,
    //     max: maxCount,
    //     axisLabel: {
    //       formatter: function(value) {
    //         return value; // 对订单数量不进行格式化
    //       }
    //     }
    //   }
    // ],
    // series: [
    //   {
    //     name: '营业额',
    //     type: 'line',
    //     stack: 'Total',
    //     data: this.dateAmount,
    //     itemStyle: {
    //       color: '#F32A23',  // 设置折线颜色为红色
    //     },
    //     yAxisIndex: 0, // 指向第一个Y轴（营业额）
    //   },
    //   {
    //     name: '订单数量',
    //     type: 'line',
    //     stack: 'Total',
    //     data: this.dateCount,
    //     itemStyle: {
    //       color: '#FEB900',  // 设置折线颜色为黄色
    //     },
    //     yAxisIndex: 1, // 指向第二个Y轴（订单数量）
    //   }
    // ]
  };

  // 全局监听图表大小变化
  window.addEventListener('resize', () => {
    this.chartInstance.resize();
  });

  this.chartInstance.setOption(option);
},
    initChartCategory() {
        const chartDom = this.$refs.chartCategory;
      this.chartInstanceCate = echarts.init(chartDom);

      const option = {
        xAxis: {
          type: 'category',
          data: this.yearDate,
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            "formatter": function(value) {
      return (value / 10000).toFixed(2) + ' w'; // 将值除以10000并添加单位
    }
          },
        },
        grid: {
        top:'5%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        series: [
          {
            data: this.yearAmount,
            type: 'bar',
            itemStyle: {
              // 渐变色
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: '#FF5851' }, // 0% 处的颜色
                  { offset: 1, color: '#E9011B' } // 100% 处的颜色
                ],
                global: false // 缺省为 false
              },
              barBorderRadius: [5, 5, 5, 5] // 圆柱效果
            },
            barWidth: '30%', // 柱状图宽度
          }
        ]
      };
//全局监听echart图表变化，可能会影响性能，
window.addEventListener('resize', function () {
  myChart.resize();
});
      this.chartInstanceCate.setOption(option);
    },
        onClickLeft() {
            this.$router.back()
        },
        onLoad() {
                 let params = {};
				params['page_num'] = this.page;
				params['page_size'] = this.pageSize;

				params['code'] = this.type;
        this.$http.get(ALLIANCE_SHOP_LIST, {params:params})
				.then(res => {
				  const {
				    list
				  } = res.data;
                  this.total_count=res.data.pages.total_count
				  if(list && list.length) {
				     this.page++;
				     this.shopList = this.shopList.concat(list);

				     // 加载状态结束
				     this.loading = false;
				     if(list.length < this.pageSize) {
				      this.finished = true;
				     }
				  }else {
				    this.finished = true;
				  }
				})
    },
    },
}
</script>
<style lang="scss" scoped>
.gold-shop-wrap {
    min-height: calc(100vh - 46px);
    padding-top: 46px;
    background: #F2F4F5;

    ::v-deep .van-nav-bar .van-icon {
        color: #333333;
    }

    ::v-deep .van-nav-bar__arrow {
        font-size: 20px;
    }
}

.profit_core_title1 {
    width: 95%;
    margin: 0 auto;
    font-family: PingFangSC, PingFang SC;
    font-weight: 600;
    font-size: .28rem;
    color: #333333;
    // line-height: 18px;
    text-align: left;
    font-style: normal;
    padding-top: .32rem;
}

.profit_core {
    width: 95%;
    margin: 0 auto;
    margin-top: 0.2rem;
    box-sizing: border-box;
    border-radius: 0.2rem;
    // border: 0.01rem solid #999;
    background: url("../../../images/mine/mine-team-bg.png") no-repeat;
    background-position: center;
    background-size: cover;
    color: #fff;

    .profit_core_title {
        // font-size: .28rem;
        display: flex;
        justify-content: space-between;
        // margin-bottom: 0.38rem;
        padding: 0.24rem 0;

        div {
            font-weight: 400;
            font-size: .28rem;
            color: #fff;
            text-align: center;
            padding-left: 0.2rem;
        }
    }

    .profit_core_amt {
        display: flex;
        flex-wrap: nowrap;
        justify-content: space-between;

        .after {
            position: relative;

            &::after {
                position: absolute;
                right: 0;
                top: 0;
                bottom: 0;
                margin: auto;
                content: '';
                height: 0.5rem;
                width: 1px;
                background: rgba(255,255,255,0.2);
            }
        }

        .profit_core_amt_list {
            width: 30%;
            text-align: center;
            margin-bottom: 0.2rem;
            line-height: 0.6rem;
            font-size: 0.24rem;
            color: #D9D9D9;
            div:first-child{
                font-size: .28rem;
            }
        }
    }

}

.order_all {
    width: 95%;
    margin: 0 auto;
    margin-top: 0.2rem;
    // border: 0.01rem solid #999;
    border-radius: 0.16rem;
    background: #fff;

    .order_name_return {
        display: flex;
        justify-content: space-between;
        font-size: 0.28rem;
        padding: 0.32rem;
        padding-bottom: 0;
        // border-bottom: 0.01rem solid #999;
        box-sizing: border-box;

        .order_name_left {
            width:48%;
            overflow:hidden;
            text-overflow:ellipsis;
            white-space:nowrap;
            font-weight: bold;
        }

        .balance_amt {
            // margin-top: 0.3rem;
            // font-weight: bold;
            width:48%;
            overflow:hidden;
            text-overflow:ellipsis;
            white-space:nowrap;
            text-align: right;
            font-size: 0.24rem;
            font-family: PingFangSC, PingFang SC;
            color: #666;
        }

        // &_right {
        //     font-size: 0.25rem;
        // }
    }

    .ectension_list {
        padding: 0.32rem;
        // padding-top: 0.2rem;
        display: flex;
        justify-content: space-between;

        .ectension_list_item {
            width: 25%;
            text-align: center;
            font-size: 0.28rem;
            line-height: 0.6rem;
            .ectension_list_item_title{
                font-size: .24rem;
                color: #666;
            }
        }
    }
}
.chart_box{
    background: #fff;
    width: 95%;
    margin: 0 auto;
    margin-top: .2rem;
    padding: .2rem 0;
    box-sizing: border-box;
    border-radius: .1rem;
}
</style>
